import React, {Component, Fragment} from 'react';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import {connect} from 'dva';
import {Link} from 'dva/router';
import {
    Button,
    Menu,
    Dropdown,
    Icon,
    Row,
    Col,
    Steps,
    Card,
    Popover,
    Badge,
    Table,
    Tooltip,
    Divider,
    Radio,
    Select,
    Modal,
    Form, Input,
    notification,
    Popconfirm,
    List,
} from 'antd';
const FormItem = Form.Item;
const {Option} = Select;
import classNames from 'classnames';
import DescriptionList from 'components/DescriptionList';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './OrderDetail.less';
import G from '../../utils/g';
import {status, statusMap} from './orderStatus';
import SendGoods from './SendGoods';
import PayType from './PayType';
const {TextArea} = Input;


const {Step} = Steps;
const {Description} = DescriptionList;
const ButtonGroup = Button.Group;

const getWindowWidth = () => window.innerWidth || document.documentElement.clientWidth;

const action = (
    <Fragment>
        <ButtonGroup>
            <Button>发货</Button>
            <Button>备注</Button>
            <Button>取消</Button>
            <Button>延长物流</Button>
        </ButtonGroup>
        <Button type="primary" onClick={this.bindShowPop}>发货</Button>
    </Fragment>
);


const customDot = (dot, {status}) => dot;


@connect(({orderDetail, loading}) => ({
    orderDetail,
    loading: loading.effects['orderDetail/fetchAdvanced'],
}))
@Form.create()
export default class OrderDetail extends Component {
    state = {
        operationkey: 'tab1',
        stepDirection: 'horizontal',
        selectedRows: [],
        showSendGoods: false,
        expressShow: false,
        expressList: [], //物流信息列表
    };

    componentDidMount() {
        const {dispatch, location} = this.props;
        this.id = G.getUrlValue('id', location.search);
        if (typeof this.id == 'undefined') {
            notification.error({
                message: '页面错误',
                description: '订单ID不能为空',
            });
        } else {
            dispatch({
                type: 'orderDetail/fetch',
                payload: {
                    id: this.id
                }
            });
        }


        this.setStepDirection();
        window.addEventListener('resize', this.setStepDirection);
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.setStepDirection);
        this.setStepDirection.cancel();
    }

    onOperationTabChange = key => {
        this.setState({operationkey: key});
    };
    handleCancel = ()=> {
        this.setState({
            popShow: false
        });
    }
    bindShowPop = ()=> {
        this.setState({
            popShow: true
        });
    }

    @Bind()
    @Debounce(200)
    setStepDirection() {
        const {stepDirection} = this.state;
        const w = getWindowWidth();
        if (stepDirection !== 'vertical' && w <= 576) {
            this.setState({
                stepDirection: 'vertical',
            });
        } else if (stepDirection !== 'horizontal' && w > 576) {
            this.setState({
                stepDirection: 'horizontal',
            });
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
            }
        });
    }

    handleSendGoods = ()=> {
        this.setState({
            showSendGoods: true
        });
    };

    bindHideSendGoods = ()=> {
        this.setState({
            showSendGoods: false
        });
    };

    bindChangeInfo = (params)=> {
        const {dispatch} = this.props;
        dispatch({
            type: 'orderDetail/changeInfo',
            payload: params
        });
    };

    handleExPressShow = (expressContent)=> {
        this.setState({
            expressShow: true,
            expressList: Array.isArray(expressContent) ? expressContent : []
        });
    };

    handleExpressHide = ()=> {
        this.setState({
            expressShow: false
        });
    };

    render() {

        const columns = [
            {
                title: '商品图片',
                dataIndex: 'img',
                key: 'img',
                render: (val)=> {
                    return <img src={val} width={40}/>
                }
            },
            {
                title: '商品名称',
                dataIndex: 'name',
                key: 'name',
                render: (val, record)=> {
                    return <Link to={`/goods/goods-add?id=${record.goodsId}`}>{val}</Link>
                }
            },
            {
                title: '规格',
                render: (v, record)=> {
                    let sku = '';
                    for (let key in record.sku) {
                        sku += key + ':' + record.sku[key] + ' ';
                    }
                    return sku;
                }
            },
            {
                title: '单价',
                dataIndex: 'unit_price',
                key: 'unit_price',
            },
            {
                title: '数量',
                dataIndex: 'count',
                key: 'count',
            },
            {
                title: '优惠',
                render: (text, record)=> {
                    return <div>{ Number(record.couponPrice) + Number(record.promotionPrice) }</div>
                }
            },
            {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                render: text => <Badge status={statusMap[text]} text={status[text]}/>,
            },
            {
                title: '物流|单号',
                render: (a, record)=> {
                    return record.expressName ? <div>{record.expressName} | {record.expressNo}</div> : null
                }
            },
            {
                title: '发货时间',
                dataIndex: 'expressTime',
            },
            {
                title: '金额',
                dataIndex: 'price',
                key: 'price',
            },
            {
                title: '操作',
                render: (a, record)=> {
                    return <div>
                        <a onClick={ ()=> {
                            this.handleExPressShow(record.expressContent)
                        } }>查看物流</a>
                        {record.status >= 200 ? <span><Divider type="vertical"/><Link
                            to={`/order/refund-detail?id=${record.refund_info[0].id}`}>处理退款</Link></span> : null}
                    </div>
                }
            },
        ];
        const {stepDirection, selectedRows, showSendGoods, expressShow, expressList} = this.state;
        const {orderDetail, loading} = this.props;
        const {getFieldDecorator} = this.props.form;

        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
            },
            getCheckboxProps: record => ({
                disabled: record.name === 'Disabled User', // Column configuration not to be checked
                name: record.name,
            }),
        };

        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 3},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 12},
            },
        };

        const stepList = [
            <Step key={100} title="等待付款"/>,
            <Step key={101} title="买家付款"/>,
            <Step key={102} title="等待发货"/>,
            <Step key={103} title="商家发货"/>,
            <Step key={104} title="交易完成"/>
        ];

        let orderStep = [];
        const orderStepLength = orderDetail.status_records.length;
        orderStep = orderDetail.status_records.map(v=> {
            return <Step title={v.status_desc} key={v.id}
                         description={<div className={classNames(styles.textSecondary, styles.stepDescription)}>
                             <div>{v.createTime}</div>
                         </div>}/>
        });
        if (orderDetail.status != 105 && orderStepLength < 4) {
            //完全流程为5个步骤，105为交易关闭订单
            let index = orderStepLength >= 2 ? orderStepLength + 1 : orderStepLength;  //可能存在没有买家付款这一步骤
            for (let i = index; i < 5; i++) {
                orderStep.push(stepList[i]);
            }
        }

        const description = (
            <DescriptionList className={styles.headerList} size="small" col="2">
                <Description term="用户昵称">{orderDetail.nickname}</Description>
                <Description term="付款方式">{PayType[orderDetail.pay_type]}</Description>
                <Description
                    term="收货信息">{orderDetail.province}{orderDetail.city}{orderDetail.area}{orderDetail.address} {orderDetail.addressee} {orderDetail.phone}</Description>
                <Description term="创建时间">{orderDetail.createTime}</Description>
                <Description term="发票信息">
                    {orderDetail.header}
                    {orderDetail.code}
                </Description>
                <Description term="买家留言">{orderDetail.buy_message}</Description>
                <Description term="我的备注">{orderDetail.remark}</Description>
            </DescriptionList>
        );

        const extra = (
            <Row>
                <Col xs={24} sm={12}>
                    <div className={styles.textSecondary}>状态</div>
                    <div className={styles.heading}>{ orderDetail.status ? status['' + orderDetail.status] : '' }</div>
                </Col>
                <Col xs={24} sm={12}>
                    <div className={styles.textSecondary}>订单金额</div>
                    <div className={styles.heading}>¥ {orderDetail.price}</div>
                </Col>
            </Row>
        );

        return (
            <PageHeaderLayout
                title={`单号：${orderDetail.orderId}`}
                logo={
                    <img alt="" src="https://gw.alipayobjects.com/zos/rmsportal/nxkuOJlFJuAUhzlMTCEe.png"/>
                }
                action={
                    <Fragment>
                        <ButtonGroup>
                            <Popconfirm
                                title={<TextArea id={`remark${orderDetail.orderId}`} rows={4} placeholder="请输入你想备注的信息"
                                                 defaultValue={orderDetail.remark}/>} okText="确定" cancelText="取消"
                                onConfirm={()=> {
                                    this.bindChangeInfo({
                                        orderId: orderDetail.orderId,
                                        remark: document.getElementById(`remark${orderDetail.orderId}`).value
                                    })
                                }}>
                                <Button>备注</Button>
                            </Popconfirm>
                            {orderDetail.status == 100 ?
                                <Popconfirm title="你确定要取消此订单？" okText="确定" cancelText="取消" onConfirm={()=> {
                                    this.bindChangeInfo({orderId: orderDetail.orderId, status: 105})
                                }}>
                                    <Button>取消</Button>
                                </Popconfirm> : null }
                            {orderDetail.status == 103 ?
                                <Popconfirm title="你确定要延长一周的收货时间吗？" okText="确定" cancelText="取消" onConfirm={()=> {
                                    this.bindChangeInfo({orderId: orderDetail.orderId, receipt_days: 7})
                                }}>
                                    <Button>延长物流</Button>
                                </Popconfirm>
                                : null}
                        </ButtonGroup>
                        {
                            orderDetail.status == 102 ?
                                <Button type="primary" onClick={this.handleSendGoods}>发货</Button> : null
                        }

                    </Fragment>
                }
                content={description}
                extraContent={extra}
            >
                <Card title="订单流程" style={{marginBottom: 24}} bordered={false}>
                    <Steps direction={stepDirection} progressDot={customDot}
                           current={orderDetail.status_records.length - 1}>
                        {
                            orderStep
                        }
                        {/*<Step title="买家下单" description={desc1} />
                         <Step title="买家付款" description={desc2} />
                         <Step title="商家发货" />
                         <Step title="交易完成" />*/}
                    </Steps>
                </Card>
                <Card title="订单商品" style={{marginBottom: 24}} bordered={false}>
                    <Table
                        rowKey="id"
                        pagination={false}
                        loading={loading}
                        dataSource={orderDetail.goods_list}
                        columns={columns}
                    />
                </Card>
                <SendGoods dispatch={this.props.dispatch} sendDispatchType="orderDetail/sendGoods"
                           show={ showSendGoods } data={orderDetail} hideSendGoods={ this.bindHideSendGoods }/>
                <Modal
                    title="物流信息"
                    visible={ expressShow }
                    onOk={this.handleExpressHide}
                    onCancel={this.handleExpressHide}
                >
                    <List
                        itemLayout="horizontal"
                        dataSource={expressList}
                        renderItem={item => (<List.Item>{item.context}{item.time}</List.Item>)}
                    ></List>
                </Modal>
            </PageHeaderLayout>
        );
    }
}
